﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;



namespace WindowTextExtractor.Utils
{
    static class ImageUtils
    {
        /// <summary>
        /// Resize the image to the specified width and height.
        /// </summary>
        /// <param name="image">The image to resize.</param>
        /// <param name="width">The width to resize to.</param>
        /// <param name="height">The height to resize to.</param>
        /// <returns>The resized image.</returns>
        public static Bitmap ResizeImage(Image image, int width, int height)
        {
            var destRect = new Rectangle(0, 0, width, height);
            var destImage = new Bitmap(width, height);

            destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            using (var graphics = Graphics.FromImage(destImage))
            {
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                using (var wrapMode = new ImageAttributes())
                {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                    graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }

            return destImage;
        }
              
        private static void ReverseWordsForRightToLeft(StringBuilder text)
        {
            var textListLines = text.ToString().Split(new char[] { '\n', '\r' });
            var regexSpaceJoiningWord = new Regex(@"(^[\p{L}-[\p{Lo}]]|\p{Nd}$)|.{2,}");

            text.Clear();
            foreach (string textLine in textListLines)
            {
                var firstWord = true;
                var isPrevWordSpaceJoining = false;
                var wordArray = textLine.Split().ToList();
                wordArray.Reverse();

                foreach (string wordText in wordArray)
                {
                    var isThisWordSpaceJoining = regexSpaceJoiningWord.IsMatch(wordText);

                    if (firstWord || (!isThisWordSpaceJoining && !isPrevWordSpaceJoining))
                    {
                        text.Append(wordText);
                    }
                    else
                    {
                        text.Append(' ').Append(wordText);
                    }

                    firstWord = false;
                    isPrevWordSpaceJoining = isThisWordSpaceJoining;
                }

                if (textLine.Length > 0)
                {
                    text.Append(Environment.NewLine);
                }
            }
        }

        

        private static Bitmap ScaleBitmapUniform(Bitmap passedBitmap, double scale)
        {
            using (var memory = new MemoryStream())
            {
                passedBitmap.Save(memory, ImageFormat.Bmp);
                memory.Position = 0;
                var bitmapimage = new BitmapImage();
                bitmapimage.BeginInit();
                bitmapimage.StreamSource = memory;
                bitmapimage.CacheOption = BitmapCacheOption.None;
                bitmapimage.EndInit();
                bitmapimage.Freeze();
                
                memory.Flush();
                
                var tbmpImg = new TransformedBitmap();
                tbmpImg.BeginInit();
                tbmpImg.Source = bitmapimage;
                tbmpImg.Transform = new ScaleTransform(scale, scale);
                tbmpImg.EndInit();
                tbmpImg.Freeze();
                return BitmapSourceToBitmap(tbmpImg);
            }
        }

        private static Bitmap BitmapSourceToBitmap(BitmapSource source)
        {
            var bmp = new Bitmap(source.PixelWidth, source.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
            var data = bmp.LockBits(new Rectangle(System.Drawing.Point.Empty, bmp.Size), ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
            source.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
            bmp.UnlockBits(data);
            return bmp;
        }

        
    }
}